package com.example.service;

import com.example.entity.Devices;
import com.example.entity.Params;
import com.example.entity.StepperMotor;
import com.example.repository.StepperMotorMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class StepperMotorService implements DeviceScheduleThreshold, DeviceValueUpdate {

    public static List<KafkaProducerService.SteppingMotor> STATUS_STEPPER_MOTOR_LIST;

    static {
        KafkaProducerService.SteppingMotor stepperMotor = new KafkaProducerService.SteppingMotor();
        stepperMotor.setClockwise(true);
        stepperMotor.setRpm(2);
        stepperMotor.setCircle(1);
        STATUS_STEPPER_MOTOR_LIST = Lists.newArrayList(stepperMotor);
    }

    @Resource
    private StepperMotorMapper stepperMotorMapper;
    @Resource
    private LightSensorService lightSensorService;


    public PageInfo<StepperMotor> findMotor(Params params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<StepperMotor> search = stepperMotorMapper.findMotor(params);
        return PageInfo.of(search);
    }

    public void addMotor(StepperMotor stepperMotor) {
        stepperMotorMapper.insert(stepperMotor);
    }

    public void deleteMotor(String Mid) {
        stepperMotorMapper.deleteById(Mid);
    }

    @Override
    public boolean threshold(Devices devices) {
        return Objects.nonNull(devices.getThreshold())
                && lightSensorService.getLightIntensity() > devices.getThreshold();
    }

    @Override
    public void statusUpdate(String status) {
        if (StringUtils.equals(status, "1")) {
            KafkaProducerService.SteppingMotor steppingMotor = new KafkaProducerService.SteppingMotor();
            steppingMotor.setClockwise(true);
            steppingMotor.setCircle(1);
            steppingMotor.setRpm(2);
            STATUS_STEPPER_MOTOR_LIST.set(0, steppingMotor);
        } else {
            KafkaProducerService.SteppingMotor steppingMotor = new KafkaProducerService.SteppingMotor();
            steppingMotor.setClockwise(false);
            steppingMotor.setCircle(1);
            steppingMotor.setRpm(2);
            STATUS_STEPPER_MOTOR_LIST.set(0, steppingMotor);
        }
    }
}
